package com.hanma.servlet;

import com.hanma.bean.*;
import com.hanma.service.*;
import com.hanma.service.impl.*;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet({"/index.do","/signIndex.do","/newsSign.do","/newsIndex.do","/comment.do","/getMore.do","/getComment.do"})
public class indexServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        HttpSession session = req.getSession();
        req.setCharacterEncoding("utf-8");
        UserService userService = new UserServiceImpl();
        CategoryService service = new CategoryServiceImpl();
        NewsService newsService = new NewsServiceImpl();
        CommentsService commentsService = new CommentsServiceImpl();
        RecordService recordService = new RecordServiceImpl();
        //查找数据，并放到域中，转发到未登录首页
        if(path.equals("/index.do")) {
            session.removeAttribute("uid");
            Integer pid = 0;
            List<Category> cateList = service.findAll(pid);
            Integer cateId = 0;
            Integer secateId = 0;
            List<Category> secateList = null;
            List<News> newsList = null;
            if(req.getParameter("cateId") != null){
                cateId = Integer.parseInt(req.getParameter("cateId"));
            }
            if(req.getParameter("secateId") != null){
                secateId = Integer.parseInt(req.getParameter("secateId"));
            }
            //搜索
            String search = req.getParameter("search");
            if(search != null && search.length() > 0 && !search.equals("null")){
                req.setAttribute("search", search);
                if(cateId==0){
                    secateList = service.findAllRec();
                }else{
                    secateList = service.findAll(cateId);
                }
                newsList = newsService.findAllSearch(search);
                Integer currentPage = 1;
                if(req.getParameter("currentPage") != null) {
                    currentPage = Integer.parseInt(req.getParameter("currentPage"));
                }
                Integer size = 4;
                Integer totalPage = newsList.size() % 4 == 0 ? newsList.size() / 4 : (newsList.size() / 4 + 1);
                Integer prePage = currentPage - 1 <= 0 ? 1 : currentPage - 1;
                Integer nextPage = currentPage + 1 >= totalPage ? totalPage : currentPage + 1;
                req.setAttribute("totalPage", totalPage);
//                req.setAttribute("currentPage", currentPage);
                req.setAttribute("prePage", prePage);
                req.setAttribute("nextPage", nextPage);
                Integer start = (currentPage - 1) * size;
                newsList = newsService.findAllSearch(search,start, size);
            }else {
                if(cateId == 0){
                    //推荐的二级分类名称
                    secateList = service.findAllRec();
                    if(secateId == 0){
                        //获取推荐新闻
                        newsList = newsService.findAllRec();
                        Integer currentPage = 1;
                        if(req.getParameter("currentPage") != null) {
                            currentPage = Integer.parseInt(req.getParameter("currentPage"));
                        }
                        Integer size = 4;
                        Integer totalPage = newsList.size() % 4 == 0 ? newsList.size() / 4 : (newsList.size() / 4 + 1);
                        Integer prePage = currentPage - 1 <= 0 ? 1 : currentPage - 1;
                        Integer nextPage = currentPage + 1 >= totalPage ? totalPage : currentPage + 1;
                        req.setAttribute("totalPage", totalPage);
                        req.setAttribute("currentPage", currentPage);
                        req.setAttribute("prePage", prePage);
                        req.setAttribute("nextPage", nextPage);
                        Integer start = (currentPage - 1) * size;
                        newsList = newsService.findAllRec(start, size);
                    }
                    else {
                        //获取二级分类下的新闻
                        newsList = newsService.findAllTwo(secateId);
                        Integer currentPage = 1;
                        if(req.getParameter("currentPage") != null) {
                            currentPage = Integer.parseInt(req.getParameter("currentPage"));
                        }
                        Integer size = 4;
                        Integer totalPage = newsList.size() % 4 == 0 ? newsList.size() / 4 : (newsList.size() / 4 + 1);
                        Integer prePage = currentPage - 1 <= 0 ? 1 : currentPage - 1;
                        Integer nextPage = currentPage + 1 >= totalPage ? totalPage : currentPage + 1;
                        req.setAttribute("totalPage", totalPage);
//                        req.setAttribute("currentPage", currentPage);
                        req.setAttribute("prePage", prePage);
                        req.setAttribute("nextPage", nextPage);
                        Integer start = (currentPage - 1) * size;
                        newsList = newsService.findAllTwo(secateId,start, size);
                    }
                } else{
                    if(secateId == 0){
                        //一级分类下的二级分类名称
                        secateList = service.findAll(cateId);
                        //获取一级分类下推荐新闻
                        newsList = newsService.findAllOne(cateId);
                        Integer currentPage = 1;
                        if(req.getParameter("currentPage") != null) {
                            currentPage = Integer.parseInt(req.getParameter("currentPage"));
                        }
                        Integer size = 4;
                        Integer totalPage = newsList.size() % 4 == 0 ? newsList.size() / 4 : (newsList.size() / 4 + 1);
                        Integer prePage = currentPage - 1 <= 0 ? 1 : currentPage - 1;
                        Integer nextPage = currentPage + 1 >= totalPage ? totalPage : currentPage + 1;
                        req.setAttribute("totalPage", totalPage);
//                        req.setAttribute("currentPage", currentPage);
                        req.setAttribute("prePage", prePage);
                        req.setAttribute("nextPage", nextPage);
                        Integer start = (currentPage - 1) * size;
                        newsList = newsService.findAllOne(cateId,start, size);
                    }
                    else{
                        //一级分类下的二级分类名称
                        secateList = service.findAll(cateId);
                        //获取二级分类下的新闻
                        newsList = newsService.findAllTwo(secateId);
                        Integer currentPage = 1;
                        if(req.getParameter("currentPage") != null) {
                            currentPage = Integer.parseInt(req.getParameter("currentPage"));
                        }
                        Integer size = 4;
                        Integer totalPage = newsList.size() % 4 == 0 ? newsList.size() / 4 : (newsList.size() / 4 + 1);
                        Integer prePage = currentPage - 1 <= 0 ? 1 : currentPage - 1;
                        Integer nextPage = currentPage + 1 >= totalPage ? totalPage : currentPage + 1;
                        req.setAttribute("totalPage", totalPage);
//                        req.setAttribute("currentPage", currentPage);
                        req.setAttribute("prePage", prePage);
                        req.setAttribute("nextPage", nextPage);
                        Integer start = (currentPage - 1) * size;
                        newsList = newsService.findAllTwo(secateId,start, size);
                    }

                }
            }
            List<News> recList = newsService.findAllRec(0,6);
            req.setAttribute("recList",recList);
            req.setAttribute("cateId",cateId);
            req.setAttribute("secateId",secateId);
            req.setAttribute("cateList",cateList);
            req.setAttribute("secateList",secateList);
            req.setAttribute("newsList",newsList);
            req.setAttribute("search", search);
            req.getRequestDispatcher("/home/index.jsp").forward(req, resp);
        }
        //查找数据，并放到域中，转发到登录首页
        else if (path.equals("/signIndex.do")){
            User user = null;
            if(req.getAttribute("user") != null){
                user = (User)req.getAttribute("user");
                Integer uid = user.getId();
                session.setAttribute("uid",uid);
            }
            Integer pid = 0;
            List<Category> cateList = service.findAll(pid);
            Integer cateId = 0;
            Integer secateId = 0;
            List<Category> secateList = null;
            List<News> newsList = null;
            if(req.getParameter("cateId") != null){
                cateId = Integer.parseInt(req.getParameter("cateId"));
            }
            if(req.getParameter("secateId") != null){
                secateId = Integer.parseInt(req.getParameter("secateId"));
            }
            String search = req.getParameter("search");
            if(search != null && search.length() > 0 && !search.equals("null")){
                if(cateId==0){
                    secateList = service.findAllRec();
                }else{
                    secateList = service.findAll(cateId);
                }
                newsList = newsService.findAllSearch(search);
                Integer currentPage = 1;
                if(req.getParameter("currentPage") != null) {
                    currentPage = Integer.parseInt(req.getParameter("currentPage"));
                }
                Integer size = 4;
                Integer totalPage = newsList.size() % 4 == 0 ? newsList.size() / 4 : (newsList.size() / 4 + 1);
                Integer prePage = currentPage - 1 <= 0 ? 1 : currentPage - 1;
                Integer nextPage = currentPage + 1 >= totalPage ? totalPage : currentPage + 1;
                req.setAttribute("totalPage", totalPage);
                req.setAttribute("currentPage", currentPage);
                req.setAttribute("prePage", prePage);
                req.setAttribute("nextPage", nextPage);
                Integer start = (currentPage - 1) * size;
                newsList = newsService.findAllSearch(search,start, size);
            }else {
                if(cateId == 0){
                    secateList = service.findAllRec();
                    if(secateId == 0){
                        newsList = newsService.findAllRec();
                        Integer currentPage = 1;
                        if(req.getParameter("currentPage") != null) {
                            currentPage = Integer.parseInt(req.getParameter("currentPage"));
                        }
                        Integer size = 4;
                        Integer totalPage = newsList.size() % 4 == 0 ? newsList.size() / 4 : (newsList.size() / 4 + 1);
                        Integer prePage = currentPage - 1 <= 0 ? 1 : currentPage - 1;
                        Integer nextPage = currentPage + 1 >= totalPage ? totalPage : currentPage + 1;
                        req.setAttribute("totalPage", totalPage);
                        req.setAttribute("currentPage", currentPage);
                        req.setAttribute("prePage", prePage);
                        req.setAttribute("nextPage", nextPage);
                        Integer start = (currentPage - 1) * size;
                        newsList = newsService.findAllRec(start, size);
                    }else {
                        newsList = newsService.findAllTwo(secateId);
                        Integer currentPage = 1;
                        if(req.getParameter("currentPage") != null) {
                            currentPage = Integer.parseInt(req.getParameter("currentPage"));
                        }
                        Integer size = 4;
                        Integer totalPage = newsList.size() % 4 == 0 ? newsList.size() / 4 : (newsList.size() / 4 + 1);
                        Integer prePage = currentPage - 1 <= 0 ? 1 : currentPage - 1;
                        Integer nextPage = currentPage + 1 >= totalPage ? totalPage : currentPage + 1;
                        req.setAttribute("totalPage", totalPage);
                        req.setAttribute("currentPage", currentPage);
                        req.setAttribute("prePage", prePage);
                        req.setAttribute("nextPage", nextPage);
                        Integer start = (currentPage - 1) * size;
                        newsList = newsService.findAllTwo(secateId,start, size);
                    }

                }else{
                    if(secateId == 0){
                        secateList = service.findAll(cateId);
                        newsList = newsService.findAllOne(cateId);
                        Integer currentPage = 1;
                        if(req.getParameter("currentPage") != null) {
                            currentPage = Integer.parseInt(req.getParameter("currentPage"));
                        }
                        Integer size = 4;
                        Integer totalPage = newsList.size() % 4 == 0 ? newsList.size() / 4 : (newsList.size() / 4 + 1);
                        Integer prePage = currentPage - 1 <= 0 ? 1 : currentPage - 1;
                        Integer nextPage = currentPage + 1 >= totalPage ? totalPage : currentPage + 1;
                        req.setAttribute("totalPage", totalPage);
                        req.setAttribute("currentPage", currentPage);
                        req.setAttribute("prePage", prePage);
                        req.setAttribute("nextPage", nextPage);
                        Integer start = (currentPage - 1) * size;
                        newsList = newsService.findAllOne(cateId,start, size);
                    }else{
                        secateList = service.findAll(cateId);
                        newsList = newsService.findAllTwo(secateId);
                        Integer currentPage = 1;
                        if(req.getParameter("currentPage") != null) {
                            currentPage = Integer.parseInt(req.getParameter("currentPage"));
                        }
                        Integer size = 4;
                        Integer totalPage = newsList.size() % 4 == 0 ? newsList.size() / 4 : (newsList.size() / 4 + 1);
                        Integer prePage = currentPage - 1 <= 0 ? 1 : currentPage - 1;
                        Integer nextPage = currentPage + 1 >= totalPage ? totalPage : currentPage + 1;
                        req.setAttribute("totalPage", totalPage);
                        req.setAttribute("currentPage", currentPage);
                        req.setAttribute("prePage", prePage);
                        req.setAttribute("nextPage", nextPage);
                        Integer start = (currentPage - 1) * size;
                        newsList = newsService.findAllTwo(secateId,start, size);
                    }

                }
            }
            List<News> recList = newsService.findAllRec(0,6);
            req.setAttribute("recList",recList);
//            req.setAttribute("uid",uid);
            req.setAttribute("cateId",cateId);
            req.setAttribute("secateId",secateId);
            req.setAttribute("cateList",cateList);
            req.setAttribute("secateList",secateList);
            req.setAttribute("newsList",newsList);
            req.setAttribute("search", search);
            req.getRequestDispatcher("/home/signIndex.jsp").forward(req, resp);
        }
        //接收查找数据，跳转到新闻页面
        else if (path.equals("/newsSign.do")) {
            Integer nid = Integer.parseInt(req.getParameter("nid"));
            News news = newsService.find(nid);
            if(session.getAttribute("uid") != null && !session.getAttribute("uid").equals("null")){
                Integer uid = (Integer) session.getAttribute("uid");
                Record record = new Record(uid,nid,news.getTitle());
                recordService.insert(record);
                User user =userService.findById(uid);
                req.setAttribute("user",user);
            }
            //增加点击量
            boolean flag =newsService.incrementNewsClickCount(nid);
            List<News> newsList = newsService.findAllTwo(news.getSeCateId(),0, 2);
            List<Comments> commentsList = commentsService.findAll(nid);
            List<News> recList = newsService.findAllRec(0,6);
            req.setAttribute("recList",recList);
            req.setAttribute("commentsList",commentsList);
            req.setAttribute("news",news);
            req.setAttribute("newsList",newsList);
            req.getRequestDispatcher("/home/news.jsp").forward(req, resp);
        }
        //提交评论
        else if (path.equals("/getComment.do")) {
            resp.setCharacterEncoding("utf-8");
            JSONObject jsonObject = new JSONObject();
            //判断是否登录
            if(session.getAttribute("uid") == null || session.getAttribute("uid").equals("null") ){
                jsonObject.put("msg","请先登录");
                resp.getOutputStream().write(jsonObject.toString().getBytes("utf-8"));
                return;
            }
            //获取用户id
            Integer uid = (Integer) session.getAttribute("uid");
            //用id获取用户信息
            User user = userService.findById(uid);
            //获取用户头像和昵称
            String img = user.getHead();
            String nickname = user.getNickname();
            //获取新闻id和评论
            Integer nid = Integer.parseInt(req.getParameter("nid"));
            String comment = req.getParameter("comment");
            //判断评论是否为空
            if(comment == null || comment.equals("")){
                jsonObject.put("msg1","请输入评论");
                resp.getOutputStream().write(jsonObject.toString().getBytes("utf-8"));
                return;
            }
            //封装评论
            Comments comments = new Comments(uid,nid,nickname,comment,img);
            //将评论插入数据库
            commentsService.insert(comments);
            //更新新闻评论数
            boolean flag = newsService.commentClick(nid);
            //获取24小时热文新闻列表
            List<News> recList = newsService.findAllRec(0,6);
            //这条新闻的评论次数
            Integer commentNum = commentsService.findAll(nid).size();
            jsonObject.put("commentNum", commentNum);
            jsonObject.put("comment", comment);
            jsonObject.put("nickname", nickname);
            jsonObject.put("img", img);
            jsonObject.put("recList",recList);
            jsonObject.put("uid","uid");
            resp.getOutputStream().write(jsonObject.toString().getBytes("utf-8"));
        }

        //加载更多
        else if (path.equals("/getMore.do")) {
            //每次加载2条
            Integer size = 2;
            //当前页
            Integer page = Integer.parseInt(req.getParameter("page"));
            //开始位置
            Integer start = (page - 1) * size;
            resp.setCharacterEncoding("utf-8");
            List<News> newsList = null;
            //新闻的一级分类和二级分类
            Integer cateId = Integer.parseInt(req.getParameter("cateId"));
            Integer seCateId = Integer.parseInt(req.getParameter("seCateId"));
            //判断从哪一个分类中拿取新闻
            if(cateId == 0){
                if(seCateId == 0){
                    newsList = newsService.findAllRec(start,size);
                }else {
                    newsList = newsService.findAllTwo(seCateId,start,size);
                }
            }else{
                if(seCateId == 0){
                    newsList = newsService.findAllOne(cateId,start,size);
                }else {
                    newsList = newsService.findAllTwo(seCateId,start,size);
                }
            }
            //获取搜索的关键字
            String search = req.getParameter("search");
            //判断搜索是否为空
            if(search != null && search.length() > 0 && !search.equals("null")){
                newsList = newsService.findAllSearch(search,start, size);
            }
            JSONArray jsonArray = new JSONArray(newsList);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("page", page);
            jsonObject.put("newsList", jsonArray);
            resp.getOutputStream().write(jsonObject.toString().getBytes("utf-8"));
        }
    }
}
